<template>
  <div class="profile-page">
    <div class="user-info">
      <div class="container">
        <div class="row">
          <div class="col-xs-12 col-md-10 offset-md-1">
            <img :src="profile.image" class="user-img" />
            <h4>{{profile.username}}</h4>
            <p>
              {{profile.bio}}
            </p>
            <nuxt-link class="btn btn-sm btn-outline-secondary action-btn" to="/settings" v-if="user && profile.username===user.username">
              <i class="ion-gear-a"></i> Edit Profile Settings
            </nuxt-link>
            <button class="btn btn-sm btn-outline-secondary action-btn" :class="{active:profile.following}" v-else @click="follow">
              <i class="ion-plus-round"></i>
              &nbsp; {{profile.following?'unFollow':'Follow'}} {{profile.username}}
            </button>
          </div>
        </div>
      </div>
    </div>
    <div class="container">
      <div class="row">
        <div class="col-xs-12 col-md-10 offset-md-1">
          <div class="articles-toggle">
            <ul class="nav nav-pills outline-active">
              <li class="nav-item">
                <nuxt-link class="nav-link" :class="{active:favorited==='my'}" exact="" :to="{name:'profile'}">My Articles</nuxt-link>
              </li>
              <li class="nav-item">
                <nuxt-link class="nav-link" :class="{active:favorited===profile.username}" exact="" :to="{name:'profile',query:{favorited:profile.username}}">Favorited Articles</nuxt-link>
              </li>
            </ul>
          </div>

          <template v-if="articles.length">
            <div
              class="article-preview"
              v-for="article in articles"
              :key="article.slug"
            >
              <div class="article-meta">
                <nuxt-link
                  class="author"
                  :to="`/profile/${article.author.username}`"
                >
                  <img :src="(article.author.image ? article.author.image : 'https://static.productionready.io/images/smiley-cyrus.jpg')" />
                </nuxt-link>
                <div class="info">
                  <nuxt-link
                    class="author"
                    :to="`/profile/${article.author.username}`"
                  >
                    {{ article.author.username }}
                  </nuxt-link>
                  <span class="date">{{ article.createdAt | date('MMM DD,YYYY') }}</span>
                </div>
                <button
                  class="btn btn-outline-primary btn-sm pull-xs-right"
                  :class="{ active: article.favorited }"
                  @click="onFavorite(article)"
                  :disabled='article.favoriteDisabled'
                >
                  <i class="ion-heart"></i> {{ article.favoritesCount }}
                </button>
              </div>
              <nuxt-link
                :to="{
                  name: 'article',
                  params: {
                    slug: article.slug,
                  },
                }"
                class="preview-link"
              >
                <h1>{{ article.title }}</h1>
                <p>{{ article.description }}</p>
                <span
                  @click="
                    $router.push({
                      name: 'article',
                      params: {
                        slug: article.slug,
                      },
                    })
                  "
                  >Read more...</span
                >
              </nuxt-link>
            </div>
          </template>
          <template v-else>
            <div class="article-preview">
              No articles are here... yet.
            </div>
          </template>

          <nav>
            <ul class="pagination" v-if="page!=1">
              <li class="page-item " :class="{active:item === page}" v-for="item in totalPage" :key="item">
                <nuxt-link class="page-link" :to="{name:'profile',query:{page:item} }">{{item}}</nuxt-link>
              </li>
            </ul>
          </nav>

        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {getAuthor,getUser} from '@/api/user'
import {getArticles,addFavorite,deleteFavorite,addFollow,deleteFollow} from '@/api/article'
import {mapState} from 'vuex'

export default {
  // middleware:'auth',
  name:"ProfileIndex",
  async asyncData({params,query}){
    const favorited = query.favorited || 'my'
    const limit = 8
    const page = Number.parseInt(query.page||1)
    const offset = (page - 1) * limit
    const author = await getAuthor(params.username)
    // try {
    //   const userRes = await getUser()
    //   // console.log(userRes)
    //   const {user} = userRes?userRes.data:null
    //   console.log(this)
    //   this.user=user
    // } catch (error) {
    //   console.log(error)
    // }
    // const tag = favorited==='my'?{author:params.username}:{favorited:params.username}
    // const {data} = await getAuthor(params.username)
    // const {data} = await getArticles({author:params.username})
    // console.log(data)
    // const [userRes,author]  = await Promise.all([
    //   getUser(),
    //   getAuthor(params.username),
    //   getArticles(tag),articleRes,
    //   getArticles({
    //     limit, // 每页大小
    //     offset: (page - 1) * limit,
    //     tag
    //   })
    // ]);
    // console.log(page,limit,offset)
    const articleRes = favorited==='my' 
      ? await getArticles({
        limit,
        offset,
        author:params.username
      }) 
      : await getArticles({
        limit,
        offset,
        favorited:params.username
      })
    // }else{
      // const articleRes = await getArticles({
      //   limit, // 每页大小
      //   offset: (page - 1) * limit,
      //   favorited:params.username
      // })
    // }
    // const {user} = userRes?userRes.data:null
    const {profile} = author.data
    const {articles,articlesCount} = articleRes.data
    articles.forEach(article => article.favoriteDisabled=false);
    // console.log(articles)
    return {
      // profile:data.profile
      // user,
      profile,
      articles,
      articlesCount,
      favorited,
      limit,
      page,
      offset
    }
  },
  watchQuery:['favorited','page'],
  computed:{
    ...mapState(['user']),
    totalPage () {
      return Math.ceil(this.articlesCount / this.limit)
    }
  },
  methods:{
    async onFavorite(article){
      // console.log(article)
      article.favoriteDisabled=true
      if(article.favorited){
        await deleteFavorite(article.slug)
        article.favorited=false
        article.favoritesCount += -1
      }else{
        await addFavorite(article.slug)
        article.favorited=true
        article.favoritesCount += 1
      }
      article.favoriteDisabled=false
    },
    async follow(){
      // this.article
      if(this.user){
        const {data} = this.profile.following ? await deleteFollow(this.profile.username) : await addFollow(this.profile.username)
        console.log(data.profile)
        this.profile=data.profile
      }else{
        this.$router.push('/register')
      }
    }
  }
}
</script>